import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class HttpPage extends StatefulWidget {
  @override
  _HttpPageState createState() => _HttpPageState();
}

class _HttpPageState extends State<HttpPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Map userInfo ={
      'name': '张三',
      'age': 24
    };
    print(userInfo is Map);
    var a = jsonEncode(userInfo); // 把Map类型数据转换成json字符串
    var b = jsonDecode('{"username":"张三", "age": 20}'); // 把json字符串转换成Map类型
    print(a is String);
    print(b is Map);
  }
  String text = '暂无数据';

  Map top250;
  void _getData() async {
    print('开始');
    setState(() {
      this.text = '加载数据中...';
    });
    String url = 'https://douban.uieee.com/v2/movie/top250';
    var result = await http.get(url);
//    print(jsonDecode(result.body));
    setState(() {
      this.top250 = jsonDecode(result.body);
      this.text = null;
//      print(this.top250['subjects']);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('网络请求'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('请求数据'),
            onPressed: _getData,
          ),
          Container(
            height: 400,
            decoration: BoxDecoration(
              border: Border.all(
                color: Colors.black
              )
            ),
            child: top250!=null?ListView.builder(
                itemCount: top250['subjects'].length,
                itemBuilder: (context, index) {
                  Map item = top250['subjects'][index];
                  return ListTile(
                      title: Text(item['title']),
                      subtitle: Text('${item['genres']}'),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(item['images']['medium']),
                    ),
                  );
                }): Text(text),
          )
        ],
      ),
    );
  }
}
